<template>
  <div class="c-bg-sgray">
    <new-search-bar class="c-bg-white" :searchFixed="true" @search="startSearch" @cancel="startSearch" :searchText="searchText" ref="searchBar" @clear='clear'></new-search-bar>
    <div class="c-pt24 c-ph24" v-if="activityList.length>0">
      <div v-for="(item,index) in activityList" v-bind:key="item.no" class="c-ph24 c-br16 c-bg-white c-p" :class="index==0 ? '':'c-mt20'">
        <div class="c-flex-row c-pv24" @click="clickItem(item, item.activityId)">
          <div class="c-ww180 c-maxh180 c-text-hidden c-br12 c-p">
            <div class="activity-status c-fs18 c-fc-white c-hh28 c-ph5 c-flex-row c-flex-center" :class="item.enrollStatus == 2?'activity-over':'activity-ing'">{{item.enrollStatus==2?'活动结束':'正在进行'}}
            </div>
            <img v-lazy='item.poster||require("../../../assets/activity_defult.png")' :key="item.poster" alt="" class="c-w100 c-h imgCloseBig">
          </div>
          <div class="c-flex-column c-w0 c-flex-grow1 c-pl20 c-justify-sb">
            <div class="c-fs24 c-pt10 c-ww-bw c-ww-ba" :class="item.name.length>40 ? 'c-text-ellipsis1' : ''">{{item.name}}</div>

            <div class="c-flex-row c-aligni-center c-fc-gray c-fs18 c-pb10">
              <span class="c-fs18 iconfont icon-cshy-shizhong c-mr10 c-mt2"></span>
              <span>{{item.enrollStartAt.substr(5, 11)}}至{{item.enrollEndAt.substr(5, 11)}}</span>
            </div>
          </div>
        </div>
        <div class="c-bd-b1-f6">
          <div class="c-fs20 c-fc-xbalck c-pb24 c-flex-row c-justify-sb c-aligni-center">
            <span class="c-fc-gray">单价：<span class="c-fs20">{{'￥' | iosPriceFilter}}</span>{{Number(item.price).toFixed(2)}}</span>
            <span>x{{item.buyNum}}</span>
          </div>
          <div class="c-flex-row c-aligni-center c-justify-sb c-pb24">
            <span class="c-fs24 c-fc-xblack">{{item.status == 2 ? '待付款：' :item.userId == userId ? '实付款：' : '来源：'}}</span>
            <span class="fc-orange c-fs24" v-if="item.userId == userId">
              <span class="c-fs20">{{'￥' | iosPriceFilter}}</span>{{Number(item.payMoney).toFixed(2)}}
            </span>
            <span class="fc-orange c-fs24" v-else>领取</span>
          </div>
          <div v-if="item.status == 2" class="c-fs24 c-pt10 c-pb24 c-flex-row c-aligni-center c-justify-end">
            <div v-if="item.status==2" class="c-fs22 c-fc-sblack cancel-button c-br25 c-ww150 c-hh50 c-flex-row c-flex-center c-mr12" @click="cancelOrder(item.orderId)">取消订单</div>
            <div v-if="item.status==2 && item.enrollNum * 1 < item.totalTicket * 1 && item.enrollStatus == 1 && item.bmstatus == 1"
              class="theme-bg c-fs22 c-fc-white c-br25 c-ww150 c-hh50 c-flex-row c-flex-center" @click="toPay(item.atId, item.activityId, item)">确认付款</div>
            <div v-if="item.status==2 && item.enrollNum * 1 >= item.totalTicket * 1" class="c-fs22 c-fc-gray cancel-button c-br25 c-ww150 c-hh50 c-flex-row c-flex-center c-mr12">余票不足</div>
          </div>
        </div>
        <div v-if="isShowGift(item)" class="c-fs22 c-pv24 c-flex-row c-lh c-fc-xblack c-aligni-center c-bd-b1-f6">
          <div class="c-mr24 c-fc-xblack c-fw-b c-fs24">赠品</div>
          <div class="c-flex-grow1">
            <div class="c-flex-row c-aligni-center c-bg-white c-justify-sb c-fs22">
              <span class="c-fs16 c-br4 c-inlineblack c-lh20 c-textAlign-c c-mr26 c-ph4 c-pv2 theme-bg-10 theme-fc">礼包</span>
              <div class="c-text-ellipsis1 c-lh26 c-fc-xblack"> 内含{{item.giftRelates.length}}个商品</div>
              <div class="c-flex-grow1 c-flex-row c-aligni-center c-justify-end">
                <div class="c-flex-row c-aligni-center theme-fc">
                  <span @click.stop="openGifts(item)">领取礼包</span>
                  <span class="iconfont c-fs14 c-pt2">&#xe635;</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <section class="c-fs22">
          <div class="c-fc-sblack c-flex-column">
            <div class="c-pt30 c-pb16 c-flex-row c-aligni-center">
              <span class="c-ww120 c-fc-gray">购票人:</span>
              <span class="c-flex-grow1 c-w0 c-text-ellipsis1 c-pr20">{{item.nickname}}</span>
              <div v-if="item.status == 1 || item.status == 0 || item.status == -1" class="c-ww150 c-hh50 c-flex-row c-flex-center coupon-button c-br25" @click="toTicketNum(item.activityId, item.identCode)">
                我的票券
              </div>
            </div>
          </div>
          <div class="c-pb16 c-flex-row">
            <span class="c-ww120 c-fc-gray">票务信息:</span>
            <span class="c-flex-grow1 c-w0">{{item.ticketName}}</span>
          </div>
          <div class="c-pt8 c-pb30 c-flex-row c-aligni-center">
            <span class="c-ww120 c-fc-gray">购票时间:</span>
            <span>{{item.enrollTime}}</span>
          </div>
          <div class="c-pt8 c-pb30 c-flex-row c-aligni-center" v-if="item.status == -3">
            <span class="c-ww120 c-fc-gray">状态:</span>
            <span>库存不足,报名失败!</span>
          </div>

        </section>
        <div class="c-pv30 c-textAlign-c c-bd-dt1-mgray c-fs24" v-if="item.refundStatus != 0 || item.status == -2 || item.status == -3">
          <span v-if="item.refundStatus!=0" class="activity-orange">{{item.refundStatus == -1 ? '退款失败' : item.refundStatus == 1 ? '退款成功' : '退款中'}}</span>
          <span class="fc-orange" v-else-if="item.status == -2">拼团中</span>
        </div>
        <div class="c-pa c-p-t0 c-p-r24 iconfont icon-yituikuan c-fs60 c-fc-gray" v-if="item.status == -4"></div>
      </div>
    </div>
    <loading-status-tem :showLoading="isLoading" :noMoreData="loadingStatus == 'NO_MORE_DATA' && !noneShow" :noData="noneShow" :noDataText="'您还没参加活动，快去报名吧~'"></loading-status-tem>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import { utilJs } from "@/utils/common.js";
export default {
  name: "MyActivity",
  components: {
    loadingStatusTem,
    newSearchBar,
  },
  props: [],
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      activityList: [],
      orderId: 0,
      noneShow: false,
      pageIndex: 1,
      pageSize: 10,
      loadingStatus: "NO_MORE_DATA", //显示加载更多LOAD_MORE 加载中 LOADING 没有更多 NO_MORE_DATA
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      isLoading: false,
      searchText: '',
      userId: localStorage.getItem("userId"),
    };
  },
  created() {
    utilJs.appShare(this);
  },
  methods: {
    isShowGift(item) {
      // status：-1：已作废， 0：待审核， 1：报名成功，2：待付款 ， -2：拼团中, -3：库存不足退款,-4：已退款
      // 有礼包 && 没有全部废弃（isDeprecated true票券全废弃） && (待审核 || 报名成功)
      return item.giftRelates && item.giftRelates.length && !item.isDeprecated && (item.status == 0 || item.status == 1)
    },
    openGifts(item) {
      this.$routerGo(this, "push", {
        path: `/activity/myTicket?activityId=${item.activityId}&identCode=${item.identCode}&asId=${0}`
      });
    },
    startSearch(e) {
      this.pageIndex = 1;
      this.activityList = [];
      this.searchText = e.searchValue;
      this.getActivityList();
    },
    getActivityList() {
      //获取我的活动列表
      if (!this.isLoading) {
        this.isLoading = true;
        // this.loadingStatus = 'LOADING';
        let $this = this;
        let data = {
          page: this.pageIndex,
          limit: this.pageSize,
          name: this.searchText
        }
        utilJs.postMethod(global.apiurl + "activities/mgActivities", data, function (
          res
        ) {
          $this.isLoading = false;
          $this.companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
          if ($this.pageIndex == 1) {
            $this.activityList = res.data.data;
          } else {
            $this.activityList = [...$this.activityList, ...res.data.data];
          }
          if ($this.activityList.length == 0) {
            $this.noneShow = true;
            $this.loadingStatus = "NO_MORE_DATA";
          } else {
            $this.noneShow = false;
          }
          if (res.data.next_page_url) {
            $this.loadingStatus = 'LOAD_MORE';
            $this.pageIndex++
          } else {
            $this.loadingStatus = "NO_MORE_DATA";
          }
        });
      }
    },
    clickItem(item, id) {
      let query = {
        ActivityNo: id
      }
      if (item.tags == 4194304 && item.status == 2) {
        query.recRelateId = item.extId;
        query.recType = 3;
        query.refereeId = item.inviteId;
        query.recId = item.recId;
      }
      //点击活动
      this.$routerGo(this, "push", {
        path: "/activity/activityDetail",
        query: query
      });
    },
    cancelOrder(orderId) {
      this.orderId = orderId;
      this.$cjConfirm({
        title: '提示',
        message: '确定取消订单？',
        onConfirm:() => {
          this.onConfirm();
        }
      })

    },
    onConfirm() {
      // 点击确定
      // 取消订单 发送请求
      let $this = this;
      utilJs.postMethod(
        global.apiurl + "orders/orderCancel",
        { orderId: this.orderId },
        function (res) {
          if (res == "OK") {
            // 成功改变状态
            $this.$showCjToast({
              text: "取消成功",
              type: "success",
            }).then(() => {
              $this.pageIndex = 1
              $this.getActivityList();
            });
          }
        }
      );
    },
    toPay(atId, activityId, item) {
      // 点击付款
      // 判断体验版是否到期，到期之后不可购买商品
      if (utilJs.alertShopExpire(this, utilJs.getTimeByDate(this.companyAuth.expireTime))) return true;
      localStorage.setItem(
        "activityEnrollInfo",
        JSON.stringify({
          activityId: activityId,
          actTicketId: atId,
          infoArr: item.unPayInfo.infoArr,
          identCode: item.unPayInfo.identCode
        })
      );
      let goQuery = {
        cId: -1,
        extId: atId,
        ckFrom: global.ckFrom.activity, // 活动进入支付页面
        isFromInvite: 0,
        isFromOrder: "TRUE",
        activityId: activityId,
        selectNum: item.buyNum,
        attendId: item.tags == '4096' ? item.extId : ''
      }
      // 拼团
      if (item.tags == 2) {
        goQuery.cId = item.groupId;
        goQuery.extId = item.collageId;
        goQuery.prodId = item.atId;
        goQuery.ckFrom = global.ckFrom.collageActivity;
        if (item.collageGroupType == 2) {
          goQuery.stepIndex = item.stepIndex;
        }
      }
      // 限时购
      if (item.tags == 8) {
        goQuery.ckFrom = global.ckFrom.flashSalesActivity;
        goQuery.pId = item.unPayInfo.sales.pId;
      }
      // 推荐有礼
      if (item.tags == 4194304) {
        goQuery.recRelateId = item.extId;
        goQuery.recType = 3;
        goQuery.refereeId = item.inviteId;
        goQuery.recId = item.recId;
      }
      this.$routerGo(this, "push", {
        path: `/homePage/course/coursePay`,
        query: goQuery
      });
    },
    toTicketNum(activityId, identCode) {
      // 点击查看票券
      this.$routerGo(this, "push", {
        path: `/activity/myTicket`,
        query: { activityId: activityId, identCode: identCode, asId: 0 }
      });
    },
    clickSearch() {
      this.$refs.searchBar.searchClick()
    },
    clear() {
      this.pageIndex = 1;
      this.searchText = '';
      this.activityList = [];
      this.getActivityList();
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "我的活动", "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("我的活动", "", shareUrl, "");
    },
    windowScrollFunction: function () {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.loadingStatus == 'LOAD_MORE') {
          that.getActivityList();
        }
      });
    },
    initData() {
      this.pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.activityList = [];
      // this.searchText = "";
      this.getActivityList();
    },
  },
  activated() {
    setDocumentTitle("我的活动");// eslint-disable-line
    // this.pageIndex = 1;
    // this.activityList = [];
    this.isLoading = false;
    // this.searchText = '';
    if (!!this.$route.query.searchText) {
      this.searchText = this.$route.query.searchText;
      this.clickSearch();
      // this.getActivityList();
      this.initData()
    } else {
      this.searchText = "";
      this.initData()
    }
    // if (!!this.$route.query.searchText) {
    //   this.searchText = this.$route.query.searchText;
    //   this.clickSearch();
    //   this.getActivityList();
    // } else {
    //   this.getActivityList();
    // }
    window.addEventListener('scroll', this.windowScrollFunction);
    this.wechatShare();
  },
  deactivated() {
    // this.searchText = "";
    // this.loadingStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.activity-status {
  position: absolute;
  bottom: 0;
  right: 0;
  border-top-left-radius: 0.3rem;
  border-bottom-right-radius: 0.3rem;
}
.activity-ing {
  background-color: #21b142;
}
.activity-over {
  background-color: #ff6669;
}
.activity-orange {
  color: #ff8a00;
}
.fc-orange {
  color: #fa703d;
}
.coupon-button {
  background: rgba(250, 112, 61, 0.08);
  color: #fa703d;
}
.cancel-button {
  background-color: rgba(0, 0, 0, 0.05);
}
.c-mt2 {
  margin-top: 0.05rem;
}
</style>
